/**
 * Created by rockyren on 14-8-27.
 */
/**
 * @module 画布点击事件处理
 */

define(function(require,exports,module){

  var cfg = require("./config");
  var LineFill = require("./polygonFill");
  var imgDataManagement = require("./base-modules/imgDataManagement");
  var ColorHandle = require("./base-modules/ColorHandle");
  var func = require("./base-modules/function");
  //@workaround 每次使用CanvasAreas都需新创建一个canvasAreas对象
  var CanvasAreas = require("./base-modules/CanvasAreas");


  /**
   * @method 画布点击事件处理函数
   * 得出当前点,创建像素管理类,然后使用多边形填充类
   * @param e 事件
   */
  exports.doClick = function(e) {
    //alert(e.data.proportions);
    //获得点击点(x,y)
    var x = e.pageX - cfg.CVS.offsetLeft;
    var y = e.pageY - cfg.CVS.offsetTop;

    var canvasAreas = new CanvasAreas();

    //根据所在区域获得对应的像素管理类
    var id = canvasAreas.getId(x,y);
    var area = canvasAreas.getArea(id);
    var imgData = cfg.CTX.getImageData(area.x,area.y,area.width,area.height);
    IDM = new imgDataManagement(imgData,area.x,area.y);

    //@test 填充颜色(暂定蓝色).应由ColorPanel提供
    //var newColor = new ColorHandle(0,0,255,255);
    var newColor = func.ColorConvert(cfg.fillColor);
    //@test 边界颜色.应由config.js提供

    var boundaryColor = func.ColorConvert(cfg.boundaryColor);


    //获由点击点获得相对坐标
    var relativeX = x%200;
    var relativeY = y%200;


    if(isInPolygon(relativeX,relativeY,boundaryColor)) {


      //根据面积数组和id输出面积
      $('#proportion .proportion-num').text(e.data.proportions[id]);


      var LF = new LineFill(IDM);
      LF.Fill(relativeX,relativeY,newColor,boundaryColor);
    }else {
      $('#proportion .proportion-num').text("NaN");
      console.log("不在多边形内");
    }




  };



});

function isInPolygon(x,y,boundaryColor) {
  var leftX = x;
  while(!IDM.getImageColor(leftX,y).isSameColor(boundaryColor)) {
    if(leftX<=0) return false;
    leftX--;
  }
  var rightX = x;
  while(!IDM.getImageColor(rightX,y).isSameColor(boundaryColor)) {
    if(rightX >= 200) return false;
    rightX++;
  }
  return true;
}